#!/bin/bash

if [ "$#" -gt 2 ]; then
    echo "usage: env.sh [BASE_PATH=<path>] [API_BASE_URL=<url>]"
    echo "  BASE_PATH: Specify a base path for web portal"
    echo "  API_BASE_URL: Specify a base url for backend service"
    echo "example: env.sh BASE_PATH=/amc API_BASE_URL=xxx"
    exit
fi

# Find value by key in command line arguments: findValueInArguments key arguments
return_value=
function findValueInArguments()
{
    local key=$1

    for argument in "${@:2}"
    do
        # Split arguments by '='
        local arg_name=$(echo $argument | cut -f1 -d=)
        local arg_value=$(echo $argument | cut -f2 -d=)   

        if [ $arg_name = $key ]; then
            return_value=$arg_value
            return 0
        fi
    done

    return_value=""
    return 1
}

# Recreate config file
filename=./env.config.js
rm -rf $filename
touch $filename

# Add begin of block
echo "window.env = {" >> $filename

# Read each line in .env file
# Each line represents key=value pairs
while read -r line || [ -n "$line" ];
do
    # Split env variables by '='
    if printf "%s\n" "$line" | grep -q -e '='; then
        var_name=$(printf "%s\n" "$line" | sed -e "s/=.*//")
        var_value=$(printf "%s\n" "$line" | sed -e "s/^[^=]*=//")
    else
        if [[ -z $line ]]; then
            echo $line >> $filename
        else
            echo "    $line" >> $filename
        fi
        continue
    fi

    # Read value of current variable if exists as Environment Variable
    value=$(printf "%s\n" "${!var_name}")

    # Otherwise use value from command line arguments
    [[ -z $value ]] && findValueInArguments $var_name "$@" && value=$return_value

    # Otherwise use value from .env file
    [[ -z $value ]] && value=$var_value
    
    # Append configuration property to JS file
    echo "    $var_name: \"$value\"," >> $filename
done < .env

# Add end of block
echo "}" >> $filename
